from apps.coffee.models import category
from rest_framework.views import APIView
from utils.response import ApiResponse

class CategoryView(APIView):
    def get(self, request):
        """
        获取所有咖啡分类信息

        参数:
            request (Request): DRF请求对象

        返回:
            APIResponse: 包含咖啡分类信息的响应

        异常:
            500: 获取数据失败
        """
        data = category.objects.all().values().order_by('-id')
        return ApiResponse(data=list(data))
    
    def post(self, request):
        """
        创建新的咖啡分类

        参数:
            request (Request): DRF请求对象，包含新的咖啡分类数据

        返回:
            APIResponse: 创建结果响应

        异常:
            400: 验证失败
            500: 创建失败
        """
        try: 
            data = request.data
            #查询data['name'],不能重复，重复后提示错误
            if category.objects.filter(name=data['name']).exists():
                return ApiResponse(code=400, msg='分类名称已存在')
            category.objects.create(
                 name=data['name'],
                pid=data['pid'],
                status=data['status']
            )
            return ApiResponse(code=200,message='创建成功')
        
        except Exception as e:
            return ApiResponse(code=500, message=str(e))
    def put(self, request, pk):
        """
        更新咖啡分类信息

        参数:
            request (Request): DRF请求对象，包含新的咖啡分类数据
            pk (int): 要更新的咖啡分类ID

        返回:
            APIResponse: 更新结果响应

        异常:
            400: 验证失败
            500: 更新失败
        """
        try:
            data  = request.data
            category_obj = category.objects.get(pk=pk)
            ##验证数据
            if not data['name'] or not data['pid'] or not data['status']:
                return ApiResponse(code=400, message='参数不全')
            # 只更新传递的数值
            if data['name']: category_obj.name = data['name']
            if data['pid']: category_obj.pid = data['pid']
            if data['status']: category_obj.status = data['status']
            category_obj.save()
            return ApiResponse(code=200,message='更新成功')
        except Exception as e:
            return ApiResponse(code=500,message=str(e))
    def delete(self, request, pk):
        """
        删除咖啡分类

        参数:
            request (Request): DRF请求对象
            pk (int): 要删除的咖啡分类ID

        返回:
            APIResponse: 删除结果响应

        异常:
            500: 删除失败
        """
        try:
            #检查是否存在子分类
            check_children = category.objects.filter(pid=pk).exists()
            if check_children:
                return ApiResponse(code=500, message='请先删除该分类下的子分类')
            
            category.objects.get(id=pk).delete()
            return ApiResponse(code=200, message='删除成功')
        except Exception as e:
            return ApiResponse(code=500, message=str(e))
        
